import data from '../../../../utils/data';
import util from '../../../../utils/utils';
import User from '../../../../utils/user';
import Dialog from '../../../../dist/dialog/dialog';
import bmap from '../../../../utils/bmap-wx.min.js';
import {
  UserHttp
} from '../../../../api/user'

const userModel = new UserHttp()
Page({
  /**
   * 页面的初始数据
   */
  type: 2, //模式,1:选择模式.自动后退.2:管理模式,不自动返回
  BMap: null,
  data: {
    initUser: true,
    activeID: 0,
    store_id: 0,
    listData: [],
  },
  /**
   * 页面载入完成
   */
  initPage: function (options) {
    let self = this;
    console.log(bmap)
    self.BMap = new bmap.BMapWX({
      ak: util.BdKey
    });
    let pages = getCurrentPages();
    if (options.id) {
      this.setData({
        activeID: options.id
      });
    }
    if (options.hasOwnProperty('store_id')) {
      this.setData({
        store_id: options.store_id
      });
    }
    if (pages.length > 1) {
      this.type = 1;
    }
    this.initData();
  },
  initData: function (ref) {
    let self = this;
    let update = ref || false;
    wx.showNavigationBarLoading();
    /**
     * 拉取基础数据资源
     */
    data.getUserAddress({
      store_id: this.data.store_id
    }, function (result) {
      self.setData({
        listData: result.data
      });
      util.closeLoading();
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 1, update);
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.initUser !== true) {
      return false;
    }
    this.initData(true);
  },
  onShow: function () {
    this.initData(true);
  },
  clickItem: function (event) {
    let self = this;
    let id = event.currentTarget.dataset.id;
    let _detail = false;
    let _data = this.data.listData;
    let pages;
    let prevPage = {};
    let app = getApp();
    if (self.type === 1) {
      self.setData({
        activeID: id,
      });
      for (let i = 0; i < _data.length; i++) {
        if (parseInt(id) === parseInt(_data[i]['addr_id'])) {
          _detail = _data[i];
        }
      }
      if (_detail !== false) {
        pages = getCurrentPages();
        prevPage = pages[pages.length - 2];
        if (prevPage.hasOwnProperty('upAddress')) {
          prevPage.upAddress(_detail);
        }
        app.globalData.tempParam = _detail;
        setTimeout(function () {
          wx.navigateBack();
        }, 100);
      } else {
        util.msg('没有找到操作的收货地址');
      }
    }
  },
  clickNotDeliveryAreaItem() {
    util.msg('该地址不在配送范围之内');
  },
  /**
   * 选择微信地址
   */
  chooseAddress: function () {
    let self = this;
    wx.chooseAddress({
      success: function (res) {
        if (res.errMsg === 'chooseAddress:ok') {
          /**
           * 获取到的地址自动添加并处理
           */
          let _data = self.data.listData;
          let tempStr = '';
          let newItem = {};
          let addToStr = res.provinceName + res.cityName + res.countyName + res.detailInfo + res.userName + res.telNumber;
          let isLocal = false;
          /**
           * 本地去重一下.如果已经存在完全一样的就不要了
           */
          for (let i = 0; i < _data.length; i++) {
            tempStr = _data[i]['province'] + _data[i]['city'] + _data[i]['county'] + _data[i]['detailInfo'] + _data[i]['user_name'] + _data[i]['phone_number'];
            if (tempStr === addToStr) {
              isLocal = true;
              break;
            }
          }
          if (isLocal === true) {
            util.msg('已存在相同的收货地址');
          } else {
            let data = {
              "addr_id": 0,
              "province": res.provinceName,
              "gender": "1",
              "active": "1",
              "city": res.cityName,
              "county": res.countyName,
              "detailinfo": res.detailInfo,
              "phone_number": res.telNumber,
              "user_name": res.userName,
              "area_info": res.provinceName + res.cityName + res.countyName,
              "address_tag": "",
            }
            self.BMap.geocoding({
              address: res.provinceName + res.cityName + res.countyName + res.detailInfo,
              fail: err => {
                util.msg("获取失败！")
              },
              success: res => {
                let location = res.originalData.result.location;
                data['longitude'] = location.lng
                data['latitude'] = location.lat
                self.httpUserAddAddr(data)
              },
            })
          };
        } else {
          util.msg(res.errMsg);
        }
      },
      fail: function (res) {
        console.log(res);
        util.msg(res.errMsg);
      }
    })
  },
  httpUserAddAddr: function (data) {
    console.log(userModel)
    return userModel.userAddAddr(data).then(res => {
      util.msg("导入成功！")
      this.initData(true);
    }).catch(err => {
      util.msg(err.msg)
    })
  },
  exportWxAddress: function (e) {
    let self = this;
    User.getUserSetting('scope.address', function () {
      self.chooseAddress();
    }, function () {
      wx.authorize({
        scope: 'scope.address',
        success: function () {
          self.chooseAddress();
        }
      });
    }, function () {
      util.msg('获取个人设置失败,稍候再试!');
    })
  },
  setDefault: function (event) {
    let self = this;
    let id = event.currentTarget.dataset.id;
    Dialog.confirm({
      title: '操作提示',
      message: '确定要设置为默认地址吗?'
    }).then(() => {
      util.request({
        url: util.api.setAcAddress,
        loading: true,
        data: {
          addr_id: id,
          active: 1
        },
        callback: function (result) {
          if (result.status === 'ok') {
            util.msg('设置默认地址成功!');
            self.initData(true);
          }
        }
      });
    }).catch(() => {
      // on cancel
    });
  },
  editAddress: function (event) {
    let id = event.currentTarget.dataset.id;
    let _detail = false;
    let _data = this.data.listData;
    for (let i = 0; i < _data.length; i++) {
      if (parseInt(id) === parseInt(_data[i]['addr_id'])) {
        _detail = _data[i];
      }
    }
    if (_detail !== false) {
      wx.navigateTo({
        url: '/pages/me/address/new/new?id=' + id + '&detail=' + JSON.stringify(_detail)
      });
    } else {
      util.msg('没有找到要编辑的收货地址');
    }
  },
  delAddress: function (event) {
    let id = event.currentTarget.dataset.id;
    let self = this;
    Dialog.confirm({
      title: '操作提示',
      message: '确定要删除这个收货地址吗?'
    }).then(() => {
      util.request({
        url: util.api.delAddress,
        loading: true,
        data: {
          addr_id: id
        },
        callback: function (result) {
          if (result.status === 'ok') {
            util.msg('删除地址成功!');
            self.initData(true);
          }
        }
      });
    }).catch(() => {
      // on cancel
    });
  },
});